import threading
import time

from core.capture.capture_mss import MSSCapture
from core.capture.capture_win32 import Win32Capture


# 这里以后可以扩展 Win32Capture / DXGICapture


class AppCore:
    def __init__(self, cfg: dict):
        self.cfg = cfg
        self._stop_evt = threading.Event()
        self._thread = None
        self.capture = None
        self.last_frame = None

        # 初始化截图器
        self._init_capture()

    def _init_capture(self):
        """根据 cfg 初始化截图器"""
        screen_cfg = self.cfg.get("screen", {})
        cap_type = screen_cfg.get("capture", "mss")
        width = screen_cfg.get("width", 320)
        height = screen_cfg.get("height", 320)

        if cap_type == "mss":
            self.capture = MSSCapture(
                monitor=screen_cfg.get("monitor", 1),
                width=width, height=height
            )
            self.capture.init_in_thread()

        elif cap_type == "win32":
            self.capture = Win32Capture(
                hwnd=None, width=width, height=height
            )
            self.capture.init_in_thread()

        else:
            raise ValueError(f"未知的 capture 类型: {cap_type}")

    def start(self):
        if self._thread and self._thread.is_alive():
            print("⚠️ AppCore 已在运行中")
            return

        self._stop_evt.clear()
        self._thread = threading.Thread(target=self._run_loop, daemon=True)
        self._thread.start()
        print("✅ AppCore 启动")

    def stop(self):
        self._stop_evt.set()
        print("🛑 AppCore 停止")

    def update_config(self, new_cfg: dict):
        """热更新配置"""
        self.cfg = new_cfg
        screen_cfg = self.cfg.get("screen", {})

        if hasattr(self.capture, "update_size"):
            print("调用 update_size:", screen_cfg.get("width"), screen_cfg.get("height"))
            self.capture.update_size(
                screen_cfg.get("width", 320),
                screen_cfg.get("height", 320)
            )

        # 判断截图方式是否变化
        cap_type = screen_cfg.get("capture", "mss")
        if not isinstance(self.capture, MSSCapture) and cap_type == "mss":
            print("🔄 截图方式改变，重新初始化")
            self._init_capture()
            return

        # 热更新截图区域大小
        if hasattr(self.capture, "update_size"):
            self.capture.update_size(
                screen_cfg.get("width", 320),
                screen_cfg.get("height", 320)
            )
            print(screen_cfg.get("width"))

    def _run_loop(self):
        # 在运行线程里重新初始化截图器
        self.capture.init_in_thread()
        while not self._stop_evt.is_set():
            frame = self.capture.grab_frame()
            self.last_frame = frame
            # time.sleep(0.03)  # 控制帧率
